package cn.hxzy.zyicon.service.impl;

import cn.hxzy.zyicon.entity.Icon;
import cn.hxzy.zyicon.entity.IconGroup;
import cn.hxzy.zyicon.entity.vo.PageBean;
import cn.hxzy.zyicon.repository.IconGroupRepository;
import cn.hxzy.zyicon.service.IconGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service("iconGroupService")
public class IconGroupServiceImpl implements IconGroupService {
    @Autowired
    private IconGroupRepository iconGroupRepository;

    @Override
    public PageBean<IconGroup> findAll(PageBean<IconGroup> pageBean) {
        Pageable pageable = PageRequest.of(pageBean.getPage() - 1, pageBean.getSize(), Sort.by(Sort.Order.desc("createTime")));
        Page<IconGroup> all = iconGroupRepository.findAll(pageable);
        pageBean.setList(all.getContent());
        pageBean.setCount(all.getTotalElements());
        pageBean.setPageCount(all.getTotalPages());
        return pageBean;
    }

    @Override
    public void save(IconGroup iconGroup) {
        iconGroupRepository.save(iconGroup);
    }

    @Override
    public void delete(Integer id) {
        iconGroupRepository.deleteById(id);
    }

    @Override
    public IconGroup findById(Integer id) {
        Optional<IconGroup> byId = iconGroupRepository.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }

    @Override
    public PageBean<IconGroup> findIconGroupByNameLike(String searchName, PageBean<IconGroup> iconGroupPageBean) {
        searchName="%"+searchName+"%";
        Pageable pageable = PageRequest.of(iconGroupPageBean.getPage() - 1, iconGroupPageBean.getSize(), Sort.by(Sort.Order.desc("createTime")));
        Page<IconGroup> all= iconGroupRepository.findIconGroupByNameLike(pageable,searchName);
        iconGroupPageBean.setList(all.getContent());
        iconGroupPageBean.setCount(all.getTotalElements());
        iconGroupPageBean.setPageCount(all.getTotalPages());
        return iconGroupPageBean;

    }

    @Override
    public void update(IconGroup iconGroup) {
        iconGroupRepository.save(iconGroup);
    }

    @Override
    public List<IconGroup> findAll1() {
        List<IconGroup> all = iconGroupRepository.findAll();
        return all;
    }
}
